package com.gr100.biz.api.loader;

import biz.yfsoft.api.ae.AE;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.jfinal.kit.PropKit;
import com.jfinal.plugin.activerecord.ActiveRecordPlugin;
import com.jfinal.plugin.c3p0.C3p0Plugin;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import java.util.Map;


/**
 * Created by YFsoft on 16/3/15.
 */
public class Loader {

    private static final Logger logger = LogManager.getLogger(Loader.class);
    //确保为单例模式

    private static Loader _instance = null;

    private Loader(){}

    public static synchronized Loader me(){
        if(_instance == null){
            _instance = new Loader();
        }
        return _instance;
    }



    //使用到的所有的数据源
    C3p0Plugin dbApi,dbEc,dbErp;
    //数据操作的jfinal插件
    ActiveRecordPlugin api,ec,erp;


    //加载成功的标示位
    private boolean _isLoaded = false;

    //数据库链接地址
    private String _dbHost = "";

    //api数据库的名字
    private String _apiDbName = "";

    //ec数据库的名字
    private String _ecDbName = "";

    //erp数据库的名字
    private String _erpDbName = "";

    //数据库的用户名
    private String _dbUser = "";

    //数据库的密码
    private String _dbPass = "";

    //开发模式，DEV、STAGING、PRODUCT
    private String _devMode = "DEV";

    private int _aeMode = 0;

    public String getDevMode(){
        return _devMode;
    }

    //初始化函数
    public final boolean init(){

        //加载成功之后，避免多次加载
        if(_isLoaded) return true;

        //加载app.config文件
        PropKit.use("app.config");
        //开发模式
        //优先加载环境变量中的配置信息
        Map map = System.getenv();

        logger.info("System Env:" + map.toString());

        _devMode = map.getOrDefault("API_MODE",PropKit.get("devMode")).toString();

        logger.info("_devMode:" + _devMode);

        String commonStr = PropKit.get(_devMode);

        JSONObject commonJson = JSON.parseObject(commonStr);

        // DEV:MODE_DEV , STAGING:MODE_STAGING , PRODUCT: MODE_PRODUCT
        _aeMode = "PRODUCT".equalsIgnoreCase(_devMode)?AE.MODE_PRODUCT:("STAGING".equalsIgnoreCase(_devMode)?AE.MODE_STAGING:AE.MODE_DEV);

        logger.info("_aeMode:" + _aeMode);
        logger.info("appkey:" + commonJson.getString("appkey"));
        logger.info("masterkey:" + commonJson.getString("masterkey"));

        AE.me().init(commonJson.getString("appkey"),commonJson.getString("masterkey"))
                .setMode(_aeMode);

        //加载开发模式下的配置
        _dbUser = commonJson.getString("user");
        _dbPass = commonJson.getString("pass");
        _dbHost = commonJson.getString("host");

        //加载开发模式下的数据库链接设置
        JSONObject dbJson = JSON.parseObject(PropKit.get(_devMode+"_DB"));
        _apiDbName = dbJson.getString("api");
        _ecDbName = dbJson.getString("ec");
        _erpDbName = dbJson.getString("erp");


        try {

            //创建数据源链接
            dbApi = new C3p0Plugin("jdbc:mysql://" +
                    _dbHost + "/" + _apiDbName +"?characterEncoding=utf8&zeroDateTimeBehavior=convertToNull",
                    _dbUser,
                    _dbPass);
            dbApi.setMaxPoolSize(30);
            dbApi.setMinPoolSize(1);
            dbApi.setInitialPoolSize(1);
            dbEc = new C3p0Plugin("jdbc:mysql://" +
                    _dbHost + "/" + _ecDbName +"?characterEncoding=utf8&zeroDateTimeBehavior=convertToNull",
                    _dbUser,
                    _dbPass);
            dbEc.setMaxPoolSize(30);
            dbEc.setMinPoolSize(1);
            dbEc.setInitialPoolSize(1);
            dbErp = new C3p0Plugin("jdbc:mysql://" +
                    _dbHost + "/" + _erpDbName +"?characterEncoding=utf8&zeroDateTimeBehavior=convertToNull",
                    _dbUser,
                    _dbPass);
            dbErp.setMaxPoolSize(30);
            dbErp.setMinPoolSize(1);
            dbErp.setInitialPoolSize(1);
            //启动数据源
            dbApi.start();
            dbEc.start();
            dbErp.start();

            //创建数据连接的插件
            api = new ActiveRecordPlugin("api",dbApi);
            ec = new ActiveRecordPlugin("ec",dbEc);
            erp = new ActiveRecordPlugin("erp",dbErp);
            erp.setShowSql(true);
            //启动插件
            api.start();
            ec.start();
            erp.start();

        }catch(Exception hex){
            logger.error(hex.getMessage());
            return false;
        }
        logger.info("loader init ok~~");

        _isLoaded = true;
        return true;

    }


}
